const App = getApp()
const util = require('../../../utils/util.js')
Page({
  data: {
    lock: true,
    billType: 0,
    orderType: '',
    desc: '',
    date: '',
    time: '',
    checked: false,
    totalAmount: '', // 实际支付
    total: '', // 合计
    intMoney: 0,
    intVal: '',
    userInfo: {
      discount: 0, // 用户优惠金额 
      linkman: '', // 联系人 
      phone: '', // 联系电话 
      appointmentTime: '', // 预约时间 
    },
    status: 0,
    status2: 0,
    png: false,
    showInvoice: false,
    showIntegral: false,
    couponsList: [],
    coupons: '',
    couponsFee: 0,
    couponsId: 0,
    billId: 0,
    goods: []
  },
  onLoad(option) {



 

    console.log(JSON.parse(option.items));
    let defaultCar = wx.getStorageSync('defaultCar');
    let userId = wx.getStorageSync('userId');
    let agent = wx.getStorageSync('agent');
    let goodsInfo = [];
    let items = JSON.parse(option.items);
    items.forEach(item => {
      goodsInfo.push({
        goodsId: item.id,
        num: 1
      })
    })
    let intMoney = 0;
    let nowDate = new Date().getTime();
    this.setData({
      merchant: option,
      defaultCar,
      goodsInfo,
      userId,
      agent,
      goods: items,
      total: option.price,
      'userInfo.linkman': defaultCar.linkman,
      'userInfo.phone': defaultCar.phone,
      'userInfo.appointmentTime': option.date + " " + option.time,
      intMoney: intMoney.toFixed(2)
    })
    this.discount()
    this.userInfo()
    // 判断如果是在电子券进来的就隐藏掉优惠券和积分抵扣
    if (option.canshu == "undefined") {

      this.setData({
        bian: true
      })
    } else {
      this.setData({
        bian: false
      })
      var yuanjia = this.data.total
      var zhekou = JSON.parse(this.data.merchant.canshu).zhekou

      var xian = (yuanjia * zhekou * 0.01).toFixed(2)
      
      this.setData({
        xianjia: xian
      })
     
      // 现价等于原价乘折扣



    }
  },
  onShow() {
    // this.discount()
    let billType = parseInt(wx.getStorageSync('billTypeId'));
    console.log(billType, typeof billType);
    if (!billType) {
      billType = 0;
    }
    this.setData({
      billType
    });
    console.log(this.data.billType);
  },
  discount() { // 优惠活动
    let {
      userId,
      agent
    } = this.data
    let params = {
      buyerId: userId,
      sellerId: agent.id,
      type: 4
    }
    App.HttpService.discount(params).then(res => {
      let data = res.data.data
      if (res.data.code == 200) {
        if (data.buyerStatus == 1 && data.sellerStatus == 1) {
          this.setData({
            'userInfo.discount': data.sellerValue
          })
        }
        this.calAmount()
      }
    })
  },
  userInfo() { // 获取积分
    let {
      userId
    } = this.data
    App.HttpService.userInfo({
      userId: userId
    }).then(res => {
      let data = res.data
      if (data.code == 200) {
        let integral = data.data.consumeInfo
        integral.score = data.data.userInfo.score
        this.setData({
          integral: integral
        })
      }
    })
  },
  calAmount() { //计算总价格
    let {
      userInfo,
      products
    } = this.data;
    let total = this.data.total;
    total = total - userInfo.discount;
    total = total.toFixed(2);
    this.setData({
      total,
      totalAmount: total
    });

  },
  // 计算出最后支付的价格
  calTotalAmount() {
    let {
      totalAmount,
      // 当前价格
      total,
      // 总价
      couponsFee,
    //  发票折扣
      intMoney
      // 折扣价格
    } = this.data;
    totalAmount = (total - couponsFee - intMoney).toFixed(2);

    if (totalAmount==0){
      this.setData({
        totalAmount:0.01
      });
}else{
      this.setData({
        totalAmount
      });
}


  },


//   //积分
//   var j = this.data.jifen
//     // 总金额  *被除数/除数 =  最大可输入积分数
//     var l = this.data.chang * (this.data.bcs / this.data.cs)
//     if(j > l) {
//   var g = l
// } else {
//   var g = j
// }
// console.log(g)
// let {
//   value
// } = e.detail
// this.setData({
//   value
// })

// if (value > g) {
//   value = g
//   this.setData({
//     value: g,

//   })
//   wx.showToast({
//     title: "抵扣金额大于总金额",
//     icon: 'none',
//     duration: 1500
//   })
// }





  inputBlur(e) { // 失去焦点事件
    let {
      key
    } = e.currentTarget.dataset
    let {
      value
    } = e.detail
    this.setData({
      [key]: value
    })
  },
  bindTextAreaBlur(e) { // 监听到新输入的值
    this.setData({
      desc: e.detail.value
    })
  },

  // 监听输入积分
  integralBlur(e) {




    let {
      value
    } = e.detail;
3
    let {
      totalAmount,
      integral,
      couponsFee
    } = this.data; // total 订单金额

    let scoreVal = (integral.score * integral.coinValue / integral.countsValue).toFixed(2); 
    // 所有积分兑换金额
    let integralVal = (Number(value) * integral.coinValue / integral.countsValue).toFixed(2);
     // 输入积分兑换金额

                  //  金额   -    优惠券
     let amount = totalAmount - couponsFee;

    amount
    if (amount==0.01){


    
      if(value<=10000){
        this.setData({
          intVal: value
        })
      }else{
        this.setData({
          intVal: 10000
        })
      
      }
   
      if (value <= 10000){
        return

      }else{
       
      }
  

    
    }
    if (scoreVal - integralVal > 0) { // 输入积分小于所有积分  输入合法
      if (amount - integralVal > 0) { // 输入积分小于订单金额
        this.setData({
          intMoney: integralVal,
          intVal: value
        })
      } else {
  

        //  金额   -    优惠券
        let amount = this.data.total - this.data.couponsFee;
         // 输入积分大于订单金额 输入积分==订单金额
        let score = Math.ceil(amount * integral.countsValue / integral.coinValue);
        this.setData({
          intMoney: amount.toFixed(2),
          intVal: score
        })
      }
    } else { // 输入积分大于所有积分 输入不合法 取所有积分
      //  金额   -    优惠券
      
  
      if (amount - scoreVal > 0) { // 所有积分小于订单金额
        this.setData({
          intMoney: scoreVal.toFixed(2),
          intVal: integral.score
        })
     
      } else { // 所有积分大于订单金额 所有积分==订单金额
  
        //  金额   -    优惠券
        let amount = this.data.total - this.data.couponsFee;

        let score = Math.ceil(amount * integral.countsValue / integral.coinValue);

        this.setData({
          intMoney: amount.toFixed(2),
          intVal: score,

        })
      
      }
    }

    this.calTotalAmount();
    console.log(this.data.intMoney);
  },
  redirectTo(e) {
    App.WxService.redirectTo('/pages/address/confirm/index', {
      ret: this.data.address_id
    })
  },
  formReset: function (e) {
    if (!this.data.lock) {
      return false;
    }
    this.setData({
      lock: false
    });
    console.log(111111111);
    let {
      userInfo,
      date,
      time,
      totalAmount,
      desc,
      goodsInfo,
      agent,
      userId,
      merchant,
      intVal,
      intMoney,
      couponsId,
      billId,
      total
    } = this.data
    if (userInfo.linkman == '') {
      this.alert('请输入联系人')
      return false
    }
    if (userInfo.phone == '') {
      this.alert('请输入联系电话')
      return false
    }
    if (intVal == '') {
      intVal = 0
    }
    let params = {
      buyerId: userId,
      sellerId: agent.id,
      goodsInfo,
      shopId: merchant.shopId,
      totalAmount,
      total,
      desc,
      userInfo,
      countsValue: intVal,
      countsAmount: intMoney,
      couponsId,
      billId,
      type: 4,
      fromId: e.detail.formId
    }

    if (!this.data.bian) {
// debugger
      var shu = JSON.parse(this.data.merchant.canshu)
      let dzqcs = {
        // 用户id
        buyerId: userId,
        // 代理商id
        sellerId: agent.id,
        // 商店id
        shopId: merchant.shopId,
        // 描述
        desc,
        // 联系人
        linkman: this.data.defaultCar.linkman,
        // 地址
        phone: this.data.defaultCar.phone,
        // 原价
        originalPrice: this.data.total,
        // 折扣
        discount: shu.zhekou,
        // 支付金额
        pay: this.data.xianjia,
        // 电子券id
        eleCouponId: shu.dzqid,
        // 地址、
        appointmentTime: this.data.userInfo.appointmentTime ,
        fromId: e.detail.formId
      }
  
      // debugger
    } else {
    
    }




    /**
     * 电子券-洗车结账
     * @param buyerId //用户id
     * @param sellerId //代理商id
     * @param shopId //商店id
     * @param desc //描述
     * @param linkman //联系人
     * @param phone //电话
     * @param address //地址
     * @param originalPrice //原价
     * @param discount //折扣
     * @param pay 支付金额
     * @param eleCouponId //电子券id
     * @param fromId //
     */

    if (this.data.bian == true) {
      App.HttpService.proOrderSave(params).then(res => {
        let data = res.data
        if (data.code == 200) {
          this.setData({
            lock: true
          });
          let config = data.data
          let prepay_id = e.detail.formId;
          let orderSn = config.orderSn;
          let template_id = 'dqB3ADXmio9LGKUWewpq91fNrFEDd-zn4lDrsRpEiR4';
          let touser = wx.getStorageSync('openid');
          if (config.active) {

            wx.navigateTo({
              url: '/pages/order/list/index?stauts=ALL&back=1'
            })
            wx.removeStorageSync('products')
          } else {
            let payconfig = {
              timeStamp: config.timeStamp,
              nonceStr: config.nonceStr,
              package: config.package,
              signType: config.signType,
              paySign: config.paySign,
            }

            payconfig.success = () => {
              App.HttpService.orderInfo({
                orderSn
              }).then(res => {
                console.log(res);
                if (res.data.code == 200) {
                  let data = res.data.data;

                  let token = data.token; // access_token
                  let orderSn = data.orderInfo.orderSn; // 订单号码
                  let payFee = data.orderInfo.payFee; // 金额
                  let consignee = data.orderInfo.consignee; // 联系人姓名
                  let phone = data.orderInfo.phone; // 联系人手机号
                  let appointmentTime = data.orderInfo.appointmentTime; // 预约时间
                  let car = data.orderInfo.car; // 车型
                  let carNo = data.orderInfo.carNo; // 车牌号
                  let shopAddress = data.orderInfo.shopAddress; // 地点
                  let shopName = data.orderInfo.shopName; // 商家名称
                  let orderDate = data.orderInfo.orderDate; // 下单时间
                  let postData = {
                    "touser": touser,
                    "template_id": template_id,
                    "form_id": prepay_id,
                    "data": {
                      "keyword1": {
                        "value": orderSn
                      },
                      "keyword2": {
                        "value": payFee
                      },
                      "keyword3": {
                        "value": consignee
                      },
                      "keyword4": {
                        "value": phone
                      },
                      "keyword5": {
                        "value": appointmentTime
                      },
                      "keyword6": {
                        "value": car
                      },
                      "keyword7": {
                        "value": carNo
                      },
                      "keyword8": {
                        "value": shopAddress
                      },
                      "keyword9": {
                        "value": shopName
                      },
                      "keyword10": {
                        "value": orderDate
                      }
                    }
                  }
                  // 发送模板消息
                  wx.request({
                    url: `https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=${token}`,
                    method: 'POST',
                    data: postData,
                    dataType: 'json',
                    success(res) {
                      console.log(res);
                    }
                  })
                }
              });
              wx.navigateTo({
                url: '/pages/order/list/index?stauts=ALL&back=1'
              })
              wx.removeStorageSync('products')
            }
            payconfig.fail = () => {
              this.setData({
                lock: true
              });
            }
            wx.requestPayment(payconfig)
          }


        } else {
          wx.showModal({
            title: '提示',
            content: data.msg,
            showCancel: false
          })
        }
      }, e => {
        wx.showModal({
          title: '提示',
          content: '服务器错误',
          showCancel: false
        })
      })


    } else {
      var shu = JSON.parse(this.data.merchant.canshu)
      let dzqcs = {
        // 用户id
        buyerId: userId,
        // 代理商id
        sellerId: agent.id,
        // 商店id
        shopId: merchant.shopId,
        // 描述
        desc,
        // 联系人
        linkman: this.data.defaultCar.linkman,
        // 地址
        phone: this.data.defaultCar.phone,
        // 原价
        originalPrice: this.data.total,
        // 折扣
        discount: shu.zhekou,
        // 支付金额
        pay: this.data.xianjia,
        // 电子券id
        eleCouponId: shu.dzqid,
        // 地址、
        appointmentTime: this.data.userInfo.appointmentTime,
        fromId: e.detail.formId,
      
      // 车牌号
      carNo: this.data.defaultCar.carCode
      }
      App.HttpService.xichedianziq(dzqcs).then(res => {
        console.log(res, "电子券洗车")
        var config = res.data.data
        // debugger
        let payconfig = {
          timeStamp: config.timeStamp,
          nonceStr: config.nonceStr,
          package: config.package,
          signType: config.signType,
          paySign: config.paySign,
        }
        wx.requestPayment({
          timeStamp: config.timeStamp,
          nonceStr: config.nonceStr,
          package: config.package,
          signType: config.signType,
          paySign: config.paySign,
          success(res) {
            wx.showToast({
              title: '支付成功',
              duration: 1000,
            })
            console.log(res, "成功")
          },
          fail(res) {
            wx.showToast({
              title: '支付失败',
              icon: 'loading',
              duration: 1000,
            })
            console.log(res, "支付失败")
          }
        })

      })

    }
  },
  alert(msg) {
    wx.showToast({
      title: msg,
      image: '../../../assets/images/warning.png',
      duration: 1500
    })
  },
  clear() {
    App.HttpService.clearCartByUser().then(res => {
      const data = res.data
      console.log(data)
    })
  },
  // 跳转到商家
  toMerchant(e) {
    let shopId = e.currentTarget.dataset.id;
    let distance = e.currentTarget.dataset.distance;
    wx.navigateTo({
      url: `/pages/merchantsList/detail/detail?shopId=${shopId}&distance=${distance}`,
    })
  },
  // 购物车详情弹窗
  setModalStatus2(e) {
    // let { status, index } = e.currentTarget.dataset
    let status = !this.data.status;
    this.setData({
      png: !this.data.png
    });
    this.setData({
      status
    });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData2: animation.export()
    })
    if (status == 1) {
      this.setData({
        showModalStatus2: true
      })
    }
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData2: animation
      })
      if (status == 0) {
        this.setData({
          showModalStatus2: false
        })
      }
    }.bind(this), 100)
  },
  // 隐藏购物车弹窗
  setModalStatus3(e) {
    // let { status, index } = e.currentTarget.dataset
    let status = 0;
    this.setData({
      png: !this.data.png
    });
    this.setData({
      status
    });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData2: animation.export()
    })
    if (status == 0) {
      this.setData({
        showModalStatus2: false
      })
    }
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData2: animation
      })
      if (status == 0) {
        this.setData({
          showModalStatus2: false
        })
      }
    }.bind(this), 100)
  },
  // 优惠券弹窗
  setModalStatus4(e) {
    let userId = this.data.userId;
    let amount = this.data.merchant.price;
    let sellerId = this.data.agent.id;
    App.HttpService.getCoupons({
      userId,
      amount,
      couponsType: 4,
      sellerId
    }).then(res => {
      console.log(res);
      if (res.data.code == 200) {
        let data = res.data.data;
        for (let i = 0; i < data.length; i++) {
          if (data[i].id == this.data.coupons) {
            data[i].checked = true;
          } else {
            data[i].checked = false;
          }
        }
        this.setData({
          couponsList: data
        });
      }
    });
    let status2 = 1;
    this.setData({
      status2
    });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(0).step()
    this.setData({
      animationData: animation.export()
    })
    if (status2 == 1) {
      this.setData({
        showModalStatus: true
      })
    }
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData2: animation
      })
      if (status2 == 0) {
        this.setData({
          showModalStatus: false
        })
      }
    }.bind(this), 100)
  },
  // 隐藏优惠券弹窗
  setModalStatus5(e) {
    // let { status, index } = e.currentTarget.dataset
    let status2 = 0;
    this.setData({
      status2
    });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export()
    })
    if (status2 == 0) {
      this.setData({
        showModalStatus: false
      })
    }
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation
      })
      if (status2 == 0) {
        this.setData({
          showModalStatus: false
        })
      }
    }.bind(this), 100)
  },
  // 选择优惠券
  chooseCoupons(e) {
    console.log(e);
    let coupons = e.currentTarget.dataset.id;
    let couponsFee = e.currentTarget.dataset.discountsfee;
    this.setData({
      coupons,
      couponsFee,
      couponsId: coupons
    });
    this.setModalStatus5();
    this.calTotalAmount();
  },
  // 是否需要发票
  chooseInvoice(e) {
    this.setData({
      showInvoice: e.detail.value
    });
  },
  // 是否使用积分
  chooseIntegral(e) {
    this.setData({
      showIntegral: e.detail.value
    });
    if (!e.detail.value) {
      this.setData({
        intMoney: 0.00,
        totalAmount: this.data.total - this.data.couponsFee
      });
    }
  },
  // 跳转到发票管理
  toInvoice() {
    wx.navigateTo({
      url: '/pages/invoice/invoice',
    })
  },
  // 监听输入联系人
  linkmanInput(e) {
    this.setData({
      'userInfo.linkman': e.detail.value
    });
  },
  // 监听输入联系电话
  phoneInput(e) {
    this.setData({
      "userInfo.phone": e.detail.value
    });
  },








})